package com.weixu.fileconver.exception;

import com.weixu.fileconver.entity.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.io.FileNotFoundException;

/**
 * 全局异常处理器
 * @Author weixu
 * @Date 2025/8/29
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理文件转换异常
     */
    @ExceptionHandler(FileConvertException.class)
    public ApiResponse<String> handleFileConvertException(FileConvertException e) {
        logger.error("文件转换异常: {}", e.getMessage(), e);
        return ApiResponse.error(e.getMessage());
    }
    
    /**
     * 处理文件未找到异常
     */
    @ExceptionHandler(FileNotFoundException.class)
    public ApiResponse<String> handleFileNotFoundException(FileNotFoundException e) {
        logger.error("文件未找到: {}", e.getMessage(), e);
        return ApiResponse.error("文件未找到: " + e.getMessage());
    }
    
    /**
     * 处理文件上传大小超限异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ApiResponse<String> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        logger.error("文件上传大小超限: {}", e.getMessage(), e);
        return ApiResponse.badRequest("上传文件大小超出限制");
    }
    
    /**
     * 处理参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ApiResponse<String> handleIllegalArgumentException(IllegalArgumentException e) {
        logger.error("参数异常: {}", e.getMessage(), e);
        return ApiResponse.badRequest("参数错误: " + e.getMessage());
    }
    
    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ApiResponse<String> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常: {}", e.getMessage(), e);
        return ApiResponse.error("系统异常: " + e.getMessage());
    }
    
    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public ApiResponse<String> handleException(Exception e) {
        logger.error("未知异常: {}", e.getMessage(), e);
        return ApiResponse.error("系统异常，请联系管理员");
    }
}